package uk.ac.aber.paws.client.state;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Vector;
import java.util.logging.Level;

import uk.ac.aber.paws.client.config.ConfigManager;
import uk.ac.aber.paws.client.constants.Constants;
import uk.ac.aber.paws.client.core.*;
import uk.ac.aber.paws.client.net.DNSLookup;
import uk.ac.aber.paws.client.util.MACAddressFinder;
import uk.ac.aber.paws.client.util.WMIOperations;


/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 8th August 2011
 * 
 * LoginInfo.java
 * 
 * This class stores various information about the client computer session such as:
 * a) computer information for this machine
 * b) information about the currently logged in user
 * c) time of last computer wake up
 * d) time of last user login
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class LoginInfo {

	private Vector<LoginEntry> loginList;
	
	class LoginEntry{
		
		private String userId;
		private long idleTime;
		private long loggedInSince;
		private long sessionID;
		private long idleExpiry;
		
		public LoginEntry(String userId, long sessionID) {
			this.userId = userId;
			this.idleTime = -1;
			this.loggedInSince = Calendar.getInstance().getTimeInMillis();
			this.sessionID = sessionID;
			this.idleExpiry = -1;
		}
		
		public String getUserId() {
			return this.userId;
		}
		
		public void setUserId(String userId) {
			this.userId = userId;
		}
		
		public long getSessionID() {
			return this.sessionID;
		}
		
		public long getIdleTime() {
			
			return this.idleTime;
		}
		
		public void setIdleTime(long idleTime) {
			this.idleTime = idleTime;
			
			// set the expiry time to current time plus 2x expected idle logging period (so 2 consecutive idle logs must be missed to trigger)
			this.idleExpiry = Calendar.getInstance().getTimeInMillis()+(1000*(Integer.parseInt(PAWSClient.getConfig().getProperty("app.main.processinterrupts.idleloggerreport"))*2));
		}
		
		public String toString() {
			
			return "userId="+userId+" ,idleTime="+idleTime+" ,loggedInSince="+loggedInSince+" ,sessionID="+sessionID+" ,idleExpiry="+idleExpiry;
		}
		
		public boolean isExpired() {
		  
			if (this.idleExpiry > -1) {
				return Calendar.getInstance().getTimeInMillis() > this.idleExpiry ? true : false;
			}
			
			return false;
		}
	}
	
	public void removeAllUsers() {
		
		loginList.clear();
	}
	
	public boolean isUserLoggedIn() {
		
		return loginList.size() > 0 ? true : false;
	}
	
	public LoginInfo() {
		
		loginList = new Vector<LoginEntry>();
	}
	
	public void addLogin(String userId, long sessionID) {
		
		if (!loginExist(userId)) {
			loginList.add(new LoginEntry(userId,sessionID));
		}
	}
	
	/*public void updateLogins(Vector<String> userList) {
	
		// clear out logged out entries
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			if (!userList.contains(entry.getUserId())) {
				loginList.remove(i);
				LoginProcessOperations.logOutUser(entry.getSessionID());
			}
		}
		
		// check for new logins
		for (int i=0;i<userList.size();i++) {
			
			if (!loginExist(userList.get(i))) {
				long sessionID = LoginProcessOperations.logInUser(userList.get(i).toUpperCase());
				
				if (sessionID > -1) {
					addLogin(userList.get(i).toUpperCase(),sessionID);
				}
			}
		}
	}*/
	
	public void setIdleTime(long idleTime, String userId) {
	
		// check if user doesn't exist, if not, could be a MAC or Linux?
		if (!loginExist(userId)) {
			
		}
		
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			if (userId.toUpperCase().equals(entry.getUserId())) {
				entry.setIdleTime(idleTime);
				break;
			}
		}
	}
	
	public boolean loginExist(String userId) {
		
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			if (entry.getUserId().equals(userId.toUpperCase())) {
				return true;
			}
		}
		
		return false;
	}
	
	public Hashtable<String,Long> getIdleTimes() {
		
		Hashtable<String,Long> idleTimes = new Hashtable<String,Long>();
		
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			idleTimes.put(entry.getUserId(), entry.getIdleTime());
			
		}
		
		return idleTimes;
	}

	public String getLoginStatus() {
		
		String loginStatus = "";
		
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			loginStatus += entry.toString() + "\n";
		}

		return loginStatus;
	}
	
	public Vector<Long> checkForExpiredSessions() {
		
		Vector<Long> expiredSessions = new Vector<Long>();
		
		for (int i=0;i<loginList.size();i++) {
			
			LoginEntry entry = loginList.get(i);
			
			if (entry.isExpired()) {
				expiredSessions.add(entry.getSessionID());
			}
		}
		
		// now delete the expired sessions based off the session ids harvested in previous loop
		for (int i=0;i<expiredSessions.size();i++) {	
			LoginEntry entry = loginList.get(i);
			
			if (expiredSessions.get(i) == entry.getSessionID()) {
				loginList.remove(entry);
			}
		}	
		
		return expiredSessions;
	}
}
